package com.shuyuntu.proposal.dao.base;

import org.hibernate.*;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * BaseDaoHib
 *
 * Created by syt05 on 2016/3/26.
 */
@Repository
public abstract class BaseDaoHib<T, PK extends Serializable> implements IBaseDao<T, PK> {
    protected Class<T> entityClass;

    @Resource(name = "sessionFactory")
    protected SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public BaseDaoHib() {
        entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public PK insert(T obj) {
        Session session = sessionFactory.getCurrentSession();
        PK id = (PK)session.save(obj);

        return id;
    }

    @Override
    public boolean delete(T obj) {
        Session session = sessionFactory.getCurrentSession();
        try {
            session.delete(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteById(PK id) {
        Session session = sessionFactory.getCurrentSession();
        try {
            T obj = session.get(entityClass, id);
            session.delete(obj);
        } catch (HibernateException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    public boolean update(T obj) {
        Session session = sessionFactory.getCurrentSession();
        try {
            session.update(obj);
        } catch (HibernateException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean insertOrUpdate(T obj) {
        Session session = sessionFactory.getCurrentSession();
        try {
            session.saveOrUpdate(obj);
        } catch (HibernateException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public long queryCount(Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        if (criterions != null) {
            for (Criterion criterion : criterions) {
                if (criterion != null) {
                    criteria.add(criterion);
                }
            }
        }
        return Long.parseLong(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
    }

    @Override
    public T queryById(PK id) {
        Session session = sessionFactory.getCurrentSession();
        T obj;
        try {
            obj = session.get(entityClass, id);
        } catch (HibernateException e) {
            e.printStackTrace();
            return null;
        }

        return obj;
    }

    @Override
    public T queryFirst(Order order, Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        if (order != null) {
            criteria.addOrder(order);
        }
        if (criterions != null) {
            for (Criterion criterion : criterions) {
                criteria.add(criterion);
            }
        }
        T t = (T)criteria.setMaxResults(1).uniqueResult();
        return t;
    }

    @Override
    public List<T> queryList(Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        if (criterions != null) {
            for (Criterion criterion : criterions) {
                criteria.add(criterion);
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List<T> list = criteria.list();

        return list;
    }

    @Override
    public List<T> queryList(Order order, Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        if (order != null) {
            criteria.addOrder(order);
        }
        if (criterions != null) {
            for (Criterion criterion : criterions) {
                criteria.add(criterion);
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List<T> list = criteria.list();

        return list;
    }

    @Override
    public List<T> queryPageList(int pageNo, int pageSize, StringBuffer rowCount, Order order,
                                 Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        for (Criterion criterion : criterions) {
            if (criterion != null) {
                criteria.add(criterion);
            }
        }
        if (rowCount != null) {
            rowCount.append(queryCount(criterions));
        }
        if (order != null) {
            criteria.addOrder(order);
        }
        List<T> list = criteria.setFirstResult((pageSize * (pageNo - 1))).setMaxResults(pageSize).list();
        return list;
    }

    @Override
    public Object queryMax(String propertyName, Criterion... criterions) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
        if (criterions != null) {
            for (Criterion criterion : criterions) {
                if (criterion != null) {
                    criteria.add(criterion);
                }
            }
        }
        Object obj = criteria.setProjection(Projections.max(propertyName)).uniqueResult();
        return obj;
    }

    @Override
    public List<T> queryListByHql(String hql) {
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List list = query.list();
        return list;
    }
}
